package com.mgq.juc.c1;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * 两阶段终止模式
 *
 *
 */

@Slf4j
public class TestTwoPhaseTermination {

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination main = new TwoPhaseTermination();
        main.start();
        //启动
        Thread.sleep(3500);
        main.stop();

    }

    static class TwoPhaseTermination {
        private Thread monitor;

        public void start() {
            monitor = new Thread(() -> {
                while (true) {
                    Thread current = Thread.currentThread();
                    if (current.isInterrupted()) {
                        log.debug("料理后事.............");
                        break;
                    }
                    try {
                        Thread.sleep(1000);//情况一.sleep打断,此时打断标记为false,需要重新设置打断标记
                        log.debug("执行监控记录"); //情况二: 正常打断,此时打断标记为true
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        //重新设置打断标记
                        current.interrupt();
                    }
                }
            });
            monitor.start();
        }

        public void stop() {
            //打断线程
            monitor.interrupt();
        }

    }
}
